﻿using IShoppingBll;
using IShoppingDal;
using ShoppingEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShoppingBll
{
    public class ShoppingCartBll : BaseBll<ShoppingCart>, IShoppingCartBll
    {
        private IShoppingCartDal _shoppingCartDal;
        private ICommodityInfoDal _commodityInfoDal;
        private IUserInfoDal _userInfoDal;
        private ICommodityTypeDal _commodityTypeDal;
        private ShoppingDbContext _dbContext;
        private IOrderInfoDal _orderInfoDal;

        public ShoppingCartBll(IShoppingCartDal shoppingCartDal, ICommodityInfoDal commodityInfoDal,IUserInfoDal userInfoDal, ICommodityTypeDal commodityTypeDal, ShoppingDbContext dbContext, IOrderInfoDal orderInfoDal) : base(shoppingCartDal)
        {
            _shoppingCartDal = shoppingCartDal;
            _commodityInfoDal = commodityInfoDal;
            _userInfoDal = userInfoDal;
            _commodityTypeDal = commodityTypeDal;
            _dbContext = dbContext;
            _orderInfoDal= orderInfoDal;
        }


        /// <summary>
        /// 购物车页面分页展示、模糊查询
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="count"></param>
        /// <param name="commodityName"></param>
        /// <returns></returns>
        public object GetShoppingCartPageList(int page, int limit, out int count, string commodityName,UserInfo userInfos)
        {
            UserInfo userInfo = _userInfoDal.GetEntity(userInfos.ID);

            // 获取数据库中用户全部没删除的数据（未真实查询）
            var shoppingCart = _shoppingCartDal.GetEntitiesDb().AsQueryable();


            var Temp = from sc in shoppingCart
                       join cd in _commodityInfoDal.GetEntitiesDb()
                       on sc.GoodsId equals cd.ID into ccTemp
                       from cc in ccTemp.DefaultIfEmpty()

                       join ct in _commodityTypeDal.GetEntitiesDb()
                       on cc.CategoryId equals ct.ID into ctTemp
                       from cct in ctTemp.DefaultIfEmpty()

                       join u in _userInfoDal.GetEntitiesDb().Where(u => !u.IsDelete)
                       on sc.UserId equals u.ID into cuTemp
                       from cu in cuTemp.DefaultIfEmpty()
                       select new
                       {
                           sc.ID,
                           cc.CommodityName,
                           sc.UserId,
                           cc.Price,
                           cct.CategoryName,
                           sc.Num,
                           cu.UserName,
                           sc.AddTime
                       };


            if (!userInfo.IsAdmin)
            {
                Temp = Temp.Where(u => u.UserId.Contains(userInfo.ID));
            }
          
            //查询出来数据的数量
            count = Temp.Count();


            //分页
            Temp = Temp.OrderBy(c => c.AddTime).Skip((page - 1) * limit).Take(limit);

            var list = Temp.ToList().Select(c => new
            {
                c.ID,
                c.CommodityName,
                c.CategoryName,
                c.Num,
                c.UserName,
                c.Price,
                TotalPrice=c.Num*c.Price,
                AddTime= c.AddTime.ToString("yyyy-MM-dd HH:mm:ss"),

            });

            return list;
        }



        /// <summary>
        /// 获取购物车信息
        /// </summary>
        /// <param name="shoppingCartId"></param>
        /// <returns></returns>
        public object GetShoppingCartOption(string shoppingCartId)
        {
            var Temp = from sc in _shoppingCartDal.GetEntitiesDb().Where(s=>s.ID.Contains(shoppingCartId))
                       join cd in _commodityInfoDal.GetEntitiesDb()
                       on sc.GoodsId equals cd.ID into ccTemp
                       from cc in ccTemp.DefaultIfEmpty()

                       join ct in _commodityTypeDal.GetEntitiesDb()
                       on cc.CategoryId equals ct.ID into ctTemp
                       from cct in ctTemp.DefaultIfEmpty()
                       select new
                       {
                           sc.ID,
                           cc.CommodityName,
                           cct.CategoryName,
                           sc.Num,
                       };
            return Temp;
        }


        /// <summary>
        /// 单件商品购买
        /// </summary>
        /// <param name="shoppingCartId"></param>
        public bool PlayShoppingCart(string shoppingCartId,UserInfo userInfos,out string msg)
        {
            UserInfo userInfo = _userInfoDal.GetEntity(userInfos.ID);
            msg = "";
            var Temp = (from sc in _shoppingCartDal.GetEntitiesDb().Where(s => s.ID.Contains(shoppingCartId))
                        join cd in _commodityInfoDal.GetEntitiesDb()
                        on sc.GoodsId equals cd.ID into ccTemp
                        from cc in ccTemp.DefaultIfEmpty()
                        select new
                        {
                            sc.ID,
                            sc.GoodsId,
                            sc.Num,
                            sc.UserId,
                            Account=sc.Num*cc.Price
                        }).FirstOrDefault();

           
            using (var transaction = _dbContext.Database.BeginTransaction())
            {
                OrderInfo orderInfo = new OrderInfo()
                {
                    ID = Guid.NewGuid().ToString(),
                    GoodsId = Temp.GoodsId,
                    UserId = Temp.UserId,
                    Amount = Temp.Account,
                    State = OrderInfo.OrderStateEnum.已下单,
                    Num = Temp.Num,
                    OrderTime = DateTime.Now,
                    IsDelete = false
                };
                if (userInfo.Balance < Temp.Account)
                {
                    msg = "您账户余额不足";
                    transaction.Rollback();
                    return false;
                }



                //添加到订单表中
                bool isSuccess1 = _orderInfoDal.Add(orderInfo);

                //删除购物车的该商品
                bool isSuccess2 = _shoppingCartDal.Delete(shoppingCartId);

                //扣除用户的金额
                userInfo.Balance = userInfo.Balance - Temp.Account;
                bool isSuccess3 = _userInfoDal.Update(userInfo);


                if (isSuccess1 && isSuccess2&& isSuccess3)
                {
                    msg = "购买成功";
                    transaction.Commit();
                    return true;
                }
                else
                {
                    msg = "购买失败";
                    transaction.Rollback();
                    return false;
                }          
            }


        }



        /// <summary>
        /// 多件商品购买
        /// </summary>
        /// <param name="shoppingCartId"></param>
        /// <returns></returns>
        public bool PlayAllShoppingCart(string[] shoppingCartId,UserInfo userInfos, out string msg)
        {
            UserInfo userInfo = _userInfoDal.GetEntity(userInfos.ID);
            msg = "";
            DateTime OrderTime = DateTime.Now;
            List<OrderInfo> orderInfos = new List<OrderInfo>();
            using (var transaction = _dbContext.Database.BeginTransaction())
            {
                int count = 0;
                int allMoney=0;  //存储总金额
                foreach (var item in shoppingCartId)
                {
                    count++;
                    var Temp = (from sc in _shoppingCartDal.GetEntitiesDb().Where(s => s.ID.Contains(item))
                                join cd in _commodityInfoDal.GetEntitiesDb()
                                on sc.GoodsId equals cd.ID into ccTemp
                                from cc in ccTemp.DefaultIfEmpty()
                                select new
                                {
                                    sc.ID,
                                    sc.GoodsId,
                                    sc.Num,
                                    sc.UserId,
                                    Account = sc.Num * cc.Price
                                }).FirstOrDefault();
                    //计算总金额
                    allMoney=allMoney+Temp.Account;

                    OrderInfo orderInfo = new OrderInfo()
                    {
                        ID = Guid.NewGuid().ToString(),
                        GoodsId = Temp.GoodsId,
                        UserId = Temp.UserId,
                        Amount = Temp.Account,
                        State = OrderInfo.OrderStateEnum.已下单,
                        Num = Temp.Num,
                        OrderTime = OrderTime,
                        IsDelete=false,
                    };
                     
                    orderInfos.Add(orderInfo);         
                }

                if (userInfo.Balance < allMoney)
                {
                    msg = "您的余额不足，无法购买";
                    transaction.Rollback();
                    return false;
                }
                //将购买的商品加入购物车
                int ResuCount = _orderInfoDal.Adds(orderInfos);
                //遍历购买的商品的，并减少商品的库存
                foreach (var item in orderInfos)
                {
                    CommodityInfo commodityInfo = _commodityInfoDal.GetEntity(item.GoodsId);
                    commodityInfo.Num = commodityInfo.Num - item.Num;
                    _commodityInfoDal.Update(commodityInfo);
                }

                userInfo.Balance = userInfo.Balance - allMoney;

                //用户减到对应的金额
                bool isSuccess2 = _userInfoDal.Update(userInfo);
                if (!isSuccess2)
                {
                    msg = "购买失败";
                    transaction.Rollback();
                    return false;
                }


                if (ResuCount == count)
                {
                    foreach (var item in shoppingCartId)
                    {
                        bool isSuccess = _shoppingCartDal.Delete(item);
                        if (!isSuccess)
                        {
                            transaction.Rollback();
                            return false;
                        }
                    }
                    msg = "购买成功";
                    transaction.Commit();
                    return true;
                }
                else
                {
                    msg = "购买失败";
                    transaction.Rollback();
                    return false;
                }
            }
            
        }




    }
}
